package com.yunkont.pigcontrol.fragment;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;

import com.yunkont.pigcontrol.R;
import com.yunkont.pigcontrol.activity.AllPigActivity;
import com.yunkont.pigcontrol.app.BaseApplicaiton;
import com.yunkont.pigcontrol.utils.Utils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import java.io.File;
import java.util.Calendar;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.yunkont.pigcontrol.net.UrlValue.downExlce;

/**
 * Created by ZJB on 2017/9/21.
 *
 * @ copyright: iwhere chengdu technology
 */

public class ThirdFragment extends Fragment {

    @Bind(R.id.tv_pigId)
    TextView tvPigId;
    @Bind(R.id.ed_startTime)
    TextView tvStartTime;
    @Bind(R.id.ed_endTime)
    TextView tvEndTime;
    private boolean isStart  =true;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_third, container, false);
        ButterKnife.bind(this, inflate);
        initView();
        initDatePicker();
        return inflate;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            initView();
        }
    }

    private void initView() {
        tvEndTime.setText("");
        tvStartTime.setText("");
        tvPigId.setText("猪编号："+ BaseApplicaiton.getInstance().getCurrentPid());
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.tvChoose, R.id.btn_Daochu,R.id.ed_startTime,R.id.ed_endTime})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvChoose:
                startActivityForResult(new Intent(getActivity(), AllPigActivity.class),100);
                break;
            case R.id.ed_startTime:
                isStart = true;
                datePickerDialog.show();
                break;
            case R.id.ed_endTime:
                isStart = false;
                datePickerDialog.show();
                break;
            case R.id.btn_Daochu:
                goSearch();
                break;
        }
    }

    private DatePickerDialog datePickerDialog;
    private void initDatePicker() {
        if (datePickerDialog == null) {
            Calendar instance = Calendar.getInstance();
            datePickerDialog = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
                    i1 = i1+1;
                    String year = i + "-";
                    String month = i1 < 10 ? ("0" + (i1)) : (i1) + "";
                    String day = i2 < 10 ? ("0" + (i2)) : (i2) + "";
                    Log.e("initDatePicker", "onDateSet: "+i+" "+i1+" "+i2 );
                    if (isStart) {
                        tvStartTime.setText(year + month +"-" + day);
                    } else {
                        tvEndTime.setText(year + month + "-" + day);
                    }
                }
            }, instance.get(Calendar.YEAR), instance.get(Calendar.MONTH), instance.get(Calendar.DAY_OF_MONTH));
        }
    }


    private void goSearch() {
        String endTime = tvEndTime.getText().toString();
        String startTime = tvStartTime.getText().toString();
        if (TextUtils.isEmpty(endTime) || TextUtils.isEmpty(startTime)) {
            Toast.makeText(getActivity(), "请输入查询时间", Toast.LENGTH_SHORT).show();
            return;
        }

        int i = Utils.daysBetween(startTime, endTime);
        if (i > 30 || i < 0) {
            Toast.makeText(getActivity(), "查询时间不超过30天,\n结束时间不得大于开始时间", Toast.LENGTH_LONG).show();
            return;
        }

        String pigId = tvPigId.getText().toString();
        if (TextUtils.isEmpty(pigId)) {
            Toast.makeText(getActivity(), "请输入猪编号", Toast.LENGTH_SHORT).show();
            return;
        }

        String end = Utils.date2TimeStamp(endTime, "yyyy-MM-dd");
        String start = Utils.date2TimeStamp(startTime, "yyyy-MM-dd");
        String absolutePath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/pigData/";
        File file = new File(absolutePath);
        if(!file.exists()){
            file.mkdirs();
        }


        OkHttpUtils.get()
                .url(downExlce)
                .addParams("pid",pigId)
                .addParams("t1",start)
                .addParams("t2",end)
                .build()
                .execute(new FileCallBack(file.getAbsolutePath(),"pigData.zip") {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(getActivity(), "下载失败："+e.toString(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(File response, int id) {
                        Toast.makeText(getActivity(), "下载成功："+response.getAbsolutePath(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void inProgress(float progress, long total, int id) {
                        super.inProgress(progress, total, id);
                    }
                });


    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 100){
            if(data != null){
                String pigId = data.getStringExtra("pigId");
                if(!TextUtils.isEmpty(pigId)){
                    tvPigId.setText("猪编号:"+pigId);
                }
            }
        }
    }
}
